package com.haizhi.factory;

import com.haizhi.redis.RedisHandler;
import com.haizhi.util.ConfUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: youfeng
 * Date: 2018-06-25
 * Time: 19:18
 */
public class RedisFactory {

    private static final Logger logger = LogManager.getLogger(RedisFactory.class);


    public static RedisHandler get(String path) throws Exception {

        Properties props = ConfUtil.getProperties(path);
        if (null == props) {
            throw new Exception("redis 配置加载失败...");
        }

        //创建jedis池配置实例
        JedisPoolConfig config = new JedisPoolConfig();

        //设置池配置项值
        config.setMaxTotal(Integer.valueOf(props.getProperty("redis.pool.maxTotal")));
        config.setMaxIdle(Integer.valueOf(props.getProperty("redis.pool.maxIdle")));
        config.setMinIdle(Integer.valueOf(props.getProperty("redis.pool.minIdle")));
        config.setMaxWaitMillis(Long.valueOf(props.getProperty("redis.pool.maxWaitMillis")));
        config.setTestOnBorrow(Boolean.valueOf(props.getProperty("redis.pool.testOnBorrow")));
        config.setTestOnReturn(Boolean.valueOf(props.getProperty("redis.pool.testOnReturn")));

        //根据配置实例化jedis池
        String password = props.getProperty("redis.password", null);
        RedisHandler redisHandler = new RedisHandler(config, props.getProperty("redis.host"),
                Integer.valueOf(props.getProperty("redis.port")),
                Integer.valueOf(props.getProperty("redis.timeout")),
                password,
                Integer.valueOf(props.getProperty("redis.db", "0")));
        logger.info("redis 初始化成功...");

        return redisHandler;
    }

}
